<!-- 总代管理 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" @changeSize="changeSize" :showExport="true" @download="getSearchList('export')"
    @changePage="changePage" @search="getSearchList" @changeTh="data.dialogVisible = true" @reset="handleReset">
    <template #form>
      <el-form-item label="总代ID：">
        <el-input type="number" v-model="data.query.operated_id" placeholder="请输入总代ID" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="总代名称：">
        <el-input v-model="data.query.operated_name" placeholder="请输入总代名称" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="app_id：">
        <el-input type="number" v-model="data.query.app_id" placeholder="请输入app_id" onKeyUp="value=value.replace(/[\W]/g,'')" />
      </el-form-item>
      <el-form-item label="">
        <el-select class="selectWidth120" v-model="data.query.date_type" placeholder="请选择">
          <el-option v-for="item in CREATETIME" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button>
      <el-button icon="Plus" type="primary" @click="add">创建总代</el-button>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content> {{item.tips}} </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'app_id'" #default="scope">
            {{ scope.row.app_id?scope.row.app_id:'-' }}
          </template>
          <template v-if="item.prop == 'status'" #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
              selectToLabel(DEMOPLAY, scope.row.status)
            }}</el-tag>
          </template>
          <template v-if="item.prop == 'is_multi_currency'" #default="scope">
            <el-tag :type="scope.row.is_multi_currency ? 'danger' : 'warning'">{{
              selectToLabel(data.generationType, scope.row.is_multi_currency)
            }}</el-tag>
          </template>
          <template v-if="item.prop == 'operator_type'" #default="scope">
            <el-tag :type="scope.row.operator_type ? 'danger' : 'success'">{{ scope.row.operator_type ? '测试':'-' }} {{ + scope.row.kol?'- kol':'' }}</el-tag>
          </template>
          <template v-if="item.prop == 'config_ggr'" #default="scope">
            <span class="marginR5" v-for="(second,two) in scope.row.config_ggr">
              {{ selectToLabel(GameBrandNum, second.platform)}}:{{second.radio}}%
            </span>
          </template>
          <template v-if="item.prop == 'share_proportion'" #default="scope">
            <div class="ratio">
              <span> {{ scope.row.share_proportion }} </span> %
            </div>
          </template>
          <template v-if="item.prop == 'created_at'" #default="scope">
            {{ setTimestampTime(scope.row.created_at) }}
          </template>
          <template v-if="item.prop == 'last_login_time'" #default="scope">
            {{ setTimestampTime(scope.row.last_login_time) }}
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="320">
        <template #header>
          <el-tooltip effect="dark" placement="top">
            <template #content>
              模拟登陆：点击可直接登录总代的后台，无需账号密码输入；<br />
              关闭/开启商户：控制商户的；关闭后商户玩家无法进入游戏；<br />
              编辑：编辑总代的信息设定及后台账号等；<br />
              删除：删除总代，数据与接口一并删除；此操作无法恢复，谨用；<br />
            </template>
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="success" v-permiss="'/system/changeManager'" size="small" @click="generalLogin(scope.row)">
            模拟登录
          </el-button>
          <el-button :type="scope.row.status ? 'info' : 'success'" v-permiss="'/system/changeManager'" size="small"
            @click="changeApi(scope.row)">
            {{ scope.row.status ? '关闭商户' : '开启商户' }}
          </el-button>
          <el-button type="warning" v-permiss="'/system/changeManager'" size="small" @click="edit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" v-permiss="'/system/destroyManager'" size="small" @click="del(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 新增  编辑  -->
  <PageDetails :show="data.formDialogShow" :checkedItem="data.checkedItem" @cancel="cancel"/>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 登录 -->
  <Login ref="refLogin" v-show="false" />
</template>

<script lang="ts" setup>
import { ref, reactive, h, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import Login from '@/views/login/login.vue'
import PageDetails from './page-details.vue'
import { selectToLabel, sortArray, setCommaNumberToArr,sortObjectArray } from '@/utils/index'
import { setTimeValue, setTimestampTime } from '@/utils/time'
import { exportToExcel } from '@/utils/export'
import { CREATETIME, DEMOPLAY, GameBrandNum } from '@/config/eunm'
import { getOperator, delOperator, editGeneralStatus } from '@/api/merchant'

import { useStore } from '@/stores/index'
const indexStore = useStore()
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    date_type: 0,
    operated_id: '',
    operated_name: '',
    app_id: '',
    date: []
  },
  list: [],
  total: 0,
  fields: [
    { label: '总代ID', prop: 'id', width: '100', visible: true, tips: '商户的ID编号，唯一' },
    { label: 'APP ID', prop: 'app_id', width: '110', visible: true, tips: t('des_21') },
    { label: '总代名称', prop: 'operator_name', width: '150', visible: true, tips: '总代名称描述' },
    { label: '后台账号', prop: 'username', width: '180', visible: true, tips: '总代的后台登录账号名称' },
    { label: '总代类型', prop: 'is_multi_currency', width: '120', visible: true, tips: '总代的区分类型' },
    { label: '测试总代', prop: 'operator_type', width: '120', visible: true, tips: '总代的区分类型' },
    { label: '状态', prop: 'status', width: '100', visible: true, tips: '账号是否封禁开启' },
    { label: '商户数量', prop: 'agent_num', width: '120', visible: true, tips: '总代下面的商户数量' },
    { label: '分成比例', prop: 'config_ggr', width: '200', visible: true, tips: '总代的分成比例' },
    { label: '返佣比例', prop: 'share_proportion', width: '120', visible: true, tips: '总代的返佣比例' },
    { label: '创建时间', prop: 'created_at', width: '180', visible: true, tips: '总代的创建生成时间' },
    { label: '最后登录时间', prop: 'last_login_time', width: '180', visible: true, tips: '总代登录后台的最近时间' }
  ],
  dialogVisible: false,
  formDialogShow: false, // 新增  编辑
  machentShow: false, // 商户类别
  checkedItem: {},
  generationType: [
    { label:'正常总代', value:0 },
    { label:'多货币总代', value:1 },
  ],
})

onMounted(async () => {
  getSearchList()
})

// 查询列表
const getSearchList = async (type?:string) => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query));
  query = setTimeValue(data.query)
  if (type && type == 'export') {
    query.size = 10000
  }
  let res = await getOperator(query)
  res.data.list?.forEach((item: any) => {
    if(item.game_ids){
      item.gameList = sortArray(setCommaNumberToArr(item.game_ids),'asc')
    }else{
      item.game_ids = []
    }
    if(item.currency_ids){
      item.currencyList = sortArray(setCommaNumberToArr(item.currency_ids),'asc')
    }else{
      item.currencyList = []
    }
    item.password = ''
    if(item.config_ggr){
      item.config_ggr = sortObjectArray(item.config_ggr,'platform','desc')
    }else{
      item.config_ggr = []
    }
  })
  // 导出
  if (type && type == 'export') {
    getExport(res.data.list)
    return
  }
  data.list = res.data.list
  data.total = res.data.total
}

// 新增
const add = () => {
  data.formDialogShow = true
}
// 修改
const edit = (row: any) => {
  data.checkedItem = row
  data.formDialogShow = true
}
// 删除
const del = async (row: any) => {
  ElMessageBox.confirm('确认删除《' + row.operator_name + '》总代？', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    await delOperator({ id: row.id })
    ElMessage.success('操作成功')
    getSearchList()
    indexStore.getOperator() //总代汇总
    indexStore.getAgent() //商户汇总
  }).catch(() => { })
}

// 总控模拟登录
const refLogin = ref<any>()
const generalLogin = async (row: any) => {
  refLogin.value.zdLogin(row.id)
}

// 开关默认
const changeApi = (row: any) => {
  let msg = row.status? '点击后此商户下的所有游戏进入维护状态,确定将此商户关闭？':row.pre_score_is_auto_close?'开启此商户的API状态，是否同步开启预存分功能？':'确认激活此商户状态？',dataRow = JSON.parse(JSON.stringify(row));
  dataRow.currency = selectToLabel(indexStore.currentArray, dataRow.currency_id)
  ElMessageBox({
    title: '提示',
    message: h('p', null, [
      h('span', null, msg),
      h('i', { style: 'color: red' }, !row.status && row.pre_score_is_auto_close?'*若要同步开启预存分功能避免再次自动关闭商户，请重新编辑预存分额度':''),
    ]),
    showCancelButton: true,
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    confirmButtonText: !row.status && row.pre_score_is_auto_close?'同步开启':'确定',
    cancelButtonText: !row.status && row.pre_score_is_auto_close?'仅开启API':'取消'
  }).then(async () => {
    dataRow.status = dataRow.status ? 0 : 1
    if(dataRow.pre_score_is_auto_close){
      dataRow.pre_score_status = 1
    }
    await editGeneralStatus(dataRow)
    ElMessage.success('操作成功')
    getSearchList()
  }).catch(async() => { 
    if(!row.status && dataRow.pre_score_is_auto_close){
      dataRow.status = dataRow.status ? 0 : 1
      dataRow.pre_score_status = 0
      await editGeneralStatus(dataRow)
      ElMessage.success('操作成功')
      getSearchList()
    }
  })
}

// 关闭弹框
const cancel = (val?: Boolean) => {
  data.formDialogShow = false
  data.checkedItem = {}
  if (val == true) {
    getSearchList()
  }
}

// 导出
const getExport = async (dataList:any) => {
  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'app_id':
          arr.push((item[x.prop]?item[x.prop]:'-') as never)
          break
        case 'is_multi_currency':
          arr.push(selectToLabel(data.generationType, item[x.prop]) as never)
          break
        case 'config_ggr':
          let name = ''
          item[x.prop].forEach((second:any) => {
            name += selectToLabel(GameBrandNum, second.platform)+':'+second.radio+'% '
          })
          arr.push(name as never)
          break
        case 'share_proportion':
          arr.push(item[x.prop]+'%' as never)
          break
        case 'operator_type':
          arr.push((item[x.prop] ? '测试':'-'  ) + (item['kol']?'- kol':'') as never)
          break
        case 'status':
          arr.push(selectToLabel(DEMOPLAY, item[x.prop]) as never)
          break
        case 'created_at':
          arr.push(setTimestampTime(item[x.prop]) as never)
          break
        case 'last_login_time':
          arr.push(setTimestampTime(item[x.prop]) as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '总代管理')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}

const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const handleReset = () => {
  data.dialogVisible = false
  data.formDialogShow = false
  data.machentShow = false
  data.query = {
    page: 1,
    size: 50,
    date_type: 0,
    date: [],
    operated_id: '',
    operated_name: '',
    app_id: '',
  }
  getSearchList()
}

</script>

<style scoped lang="scss"></style>
